from png import Writer as PngWriter


def get_pallet_dict() -> dict:
    return {
        "0": [0, 0, 0],
        "1": [255, 255, 255],
        "2": [128, 128, 128],
    }


def get_rgb_from_pallet(ascii_char):
    return get_pallet_dict().get(ascii_char, [0, 255, 0])


def get_sheet_ascii(path_to_sheet_ascii):
    with open(path_to_sheet_ascii, "r") as inputfile:
        return [list(map(lambda c: c, line.strip())) for line in inputfile]


def get_sheet_rgb(sheet_ascii):
    sheet_rgb = []
    for row in sheet_ascii:
        sheet_rgb_row = []
        for cell in row:
            rgb = get_rgb_from_pallet(cell)
            sheet_rgb_row.extend(rgb)
        sheet_rgb.append(tuple(sheet_rgb_row))
    return sheet_rgb


def get_width(sheet_rgb):
    """Unlike the height, divide by three because the tuples have extra values, one for each RGB."""
    return len(sheet_rgb[0]) // 3


def get_height(sheet_rgb):
    return len(sheet_rgb)


# TODO: Use sprite_length and pallet.
def render_sheet(
    outfile, path_to_sheet_ascii, sprite_length, pallet, greyscale, compression
):
    sheet_rgb = get_sheet_rgb(get_sheet_ascii(path_to_sheet_ascii))
    with open(outfile, "wb") as file_out:
        png_writer = PngWriter(
            get_width(sheet_rgb),
            get_height(sheet_rgb),
            greyscale=greyscale,
            compression=compression,
        )
        png_writer.write(file_out, sheet_rgb)
